package com.wechat.task;

import com.github.binarywang.wxpay.bean.result.WxPayOrderCloseResult;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.wechat.entity.User;
import com.wechat.entity.UserRechargeRecord;
import com.wechat.service.PayService;
import com.wechat.service.UserRechargeService;
import com.wechat.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 充值记录定时校验任务
 *
 * @author cgc
 * @date 2018/4/23
 */
@Component
public class CheckRechargeTask {

    private final Logger LOG = LoggerFactory.getLogger(CheckRechargeTask.class);

    @Autowired
    private UserRechargeService userRechargeService;
    @Autowired
    private PayService payService;
    @Autowired
    private UserService userService;


    @Scheduled(cron = "0 */1 * * * ?")
    public void checkRecharge() {

        LOG.info("[CheckRechargeTask]Start");

        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, -6);
        date = calendar.getTime();

        try {

            List<UserRechargeRecord> list = userRechargeService.list(null,0,null,null,null,date);

            int close = 0;
            int success = 0;

            if(list != null && list.size() > 0){
                for(UserRechargeRecord record:list){
                    try{
                        WxPayOrderQueryResult result = payService.queryOrder(record.getId(),record.getTradeNo());
                        if("SUCCESS".equals(result.getTradeState())){

                            Date payDate = new Date();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                payDate = formatter.parse(result.getTimeEnd());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            User user = userService.findById(record.getUserId());
                            if(payService.recharge(record,user,payDate,result.getTransactionId())){
                                success += 1;
                            }

                        }else if(!"USERPAYING".equals(result.getTradeState()) && !"REFUND".equals(result.getTradeState())
                                && !"CLOSED".equals(result.getTradeState())){
                            WxPayOrderCloseResult result1 = payService.closeOrder(record.getId());
                            if("SUCCESS".equals(result1.getResultCode())){
                                UserRechargeRecord record1 = new UserRechargeRecord();
                                record1.setId(record.getId());
                                record1.setTradeStatus((byte) 3);
                                userRechargeService.update(record1);
                                close += 1;
                            }
                        }
                    }catch (Exception e){
                        UserRechargeRecord record1 = new UserRechargeRecord();
                        record1.setId(record.getId());
                        record1.setTradeStatus((byte) 3);
                        userRechargeService.update(record1);
                        close += 1;
                        LOG.error("[CheckRechargeTask]stepError",e);
                        continue;
                    }
                }
            }

            LOG.info("[CheckRechargeTask]end:success=" + success + ";close=" + close);
        }catch (Exception e){
            LOG.error("[CheckRechargeTask]error",e);
        }

    }
}
